﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Negocio.Aspectos
{
    public class Contador : IContador
    {
        public int ObterContagem()
        {
            int _contador = 0;
            string conexao = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\database\Contador.mdf;Integrated Security=True;User Instance=True";

            string queryString = "SELECT MAX(numero) FROM Contador;";

            using (SqlConnection connection =
                new SqlConnection(conexao))
            {
                SqlCommand command = new SqlCommand(queryString, connection);

                try
                {
                    connection.Open();
                    _contador = Convert.ToInt32(command.ExecuteScalar());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    connection.Close();
                }
            }

            return _contador;
        }

        public void AdicionarContador()
        {
            string conexao = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\database\Contador.mdf;Integrated Security=True;User Instance=True";

            string queryString = "UPDATE Contador SET numero = @dados;";

            using (SqlConnection connection =
                new SqlConnection(conexao))
            {
                SqlCommand command = new SqlCommand(queryString, connection);
                int contagem = ObterContagem();
                command.Parameters.AddWithValue("@dados", ++contagem);

                try
                {
                    connection.Open();
                    command.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    connection.Close();
                }
            }
        }
    }
}
